#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<iostream>
using namespace std;
//int main(){
////char buff[1024];
////string s="123456";
//// snprintf(buff,sizeof(buff),"%s-%d-%d",s.c_str(),1,2);
////cout<<buff<<endl;
//    string s="你好";
//    int fds[2];
//    char buf[1024];
//    int b=pipe(fds);
//    cout<<fds[0]<<" "<<fds[1]<<endl;
//    if(b<0){
//        perror("pipe");
//        return 0;
//    }
//    pid_t pid=fork();
//    if(pid<0){
//        perror("fork");
//        return 0;
//    }
//    else if(pid==0)
//    {
//        close(fds[0]);
//        dup2(fds[1],0);
//        snprintf(buf,sizeof(buf),"%s-%d-%d",s.c_str(),0,0);
//        write(0,buf,strlen(buf));
//       // sleep(5);
//        exit(0);
//    }
//    close(fds[1]);
//    waitpid(pid,0,0);
//    read(fds[0],buf,s.size());
//    buf[s.size()]='\0';
//    cout<<buf<<endl;
//    return 0;
//}
int NUM=1024;
int N=2;
void Reader(int n){
       char buf[NUM];
       while(true)
       {
            buf[0]=0;
            read(n,buf,sizeof(buf));
            buf[strlen(buf)]='\0';
            cout<<"father get message["<<getpid()<<"]"<<buf<<endl;
       }
}
void Writer(int n){
    int num=0;
    char buf[NUM];
    string s="hello world";
    while(true)
    {         
        sleep(2);
        snprintf(buf,sizeof(buf),"%s-%d",s.c_str(),num++);
        cout<<"son send message["<<getpid()<<"]"<<buf<<endl;
        write(n,buf,sizeof(buf));
    }
}
int main()
{
    int fds[N]={0};
    int a=pipe(fds);
    //cout<<fds[1]<<" "<<fds[0]<<endl;
    if(a<0){
        perror("pipe failed");
        return 1;
    }
    pid_t pid=fork();
    if(pid<0){
        perror("fork failed");
        return 2;
    }
    else if(pid==0)
    {
        close(fds[0]);
        Writer(fds[1]);
        close(fds[1]);
        exit(0);
    }
    close(fds[1]);
    Reader(fds[0]);
    close(fds[0]);
    int status=0;
    pid_t rid=waitpid(pid,&status,0);
    if(rid < 0) return 3;
    cout << "wait child success: " << rid << " exit code: " << ((status>>8)&0xFF) << " exit signal: " << (status&0x7F) << endl;
    sleep(5);
    cout << "father quit" << endl;
    return 0;
}
